import os
import tkinter as tk
from tkinter import ttk, messagebox
from bilibili_danmu_analysis.analysis.visual_dao import VisualDao
from bilibili_danmu_analysis.utils import Utils
import webview
from bilibili_danmu_analysis.analysis.analysis_dao import AnalysisDao


class AnalyzeFrame(ttk.Frame):
    def __init__(self, parent,bvid=None):
        super().__init__(parent)
        self.bvid=bvid
        self.parent = parent
        self.init_configs()
        self._setup_ui()
        self.parent.protocol("WM_DELETE_WINDOW", self.safe_close)
    def init_file_path(self):
        self.download_path = os.path.join(os.path.dirname(__file__), "..", "download")
        if not os.path.exists(self.download_path):
            os.mkdir(self.download_path)

    def init_configs(self):
        self.init_file_path()
        self.data = {}
        self.utils = Utils()
        self.visual = VisualDao(self.download_path)
        self.analysis = AnalysisDao()
    def safe_close(self):
        self.parent.destroy()
        self.parent.quit()
        self.analysis.close_connections()

    def _setup_ui(self):
        notebook = ttk.Notebook(self)

        # 概览统计标签页
        overview_tab = ttk.Frame(notebook)
        self._create_overview_tab(overview_tab)

        # 词云分析标签页
        wordcloud_tab = ttk.Frame(notebook)
        self._create_wordcloud_tab(wordcloud_tab)

        notebook.add(overview_tab, text="数据概览")
        notebook.add(wordcloud_tab, text="词云分析")
        notebook.pack(expand=True, fill="both")

    def _create_overview_tab(self, parent):
        stats = self._calculate_statistics()

        input_frame = ttk.Frame(parent)
        input_frame.pack(pady=10, fill=tk.X, padx=5)
        bv_label= ttk.Label(input_frame, text="BV号：")
        bv_label.pack(side=tk.LEFT, padx=5, pady=5)

        self.bv_entry = ttk.Entry(input_frame)
        self.bv_entry.pack(side=tk.LEFT, padx=5, pady=5)
        self.bv_entry.insert(0, self.bvid)
        self.bv_entry.bind("<Return>", lambda event: self._verify_bvid())

        analyze_button = ttk.Button(input_frame, text="▶ 开始分析", command=self._verify_bvid)
        analyze_button.pack(side=tk.LEFT, padx=5, pady=5)

        echarts_button = ttk.Button(input_frame, text="▶ 展示弹幕时间排列图", command=lambda :self.show_line_chart())
        echarts_button.pack(side=tk.LEFT, padx=5, pady=5)

        # 统计数据表格
        self.tree = ttk.Treeview(parent, columns=("value",), show="headings")
        self.tree.heading("value", text="统计指标")
        self.tree.column("value", width=500)

        for name, value in stats.items():
            self.tree.insert("", tk.END, values=(f"{name}: {value}",))

        self.tree.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

    def _verify_bvid(self):
        self.data = {}
        bv_id = self.bv_entry.get()
        self.bvid=bv_id
        message = self.utils.validate_bvid(self.bvid)
        if message.get("code") != 200:
            self.bv_entry.delete(0, tk.END)
            messagebox.showerror("错误", message.get("message"))
            return
        self._analyze(bv_id)

    def _analyze(self,bvid):
        try:
            msg = self.analysis.get_bvid_dict(bvid)
            if msg.get("code") != 200:
                messagebox.showerror("错误", msg.get("error"))
                return
            self.data = msg.get("data")
            self.visual.genarate_line(bvid)
            self.visual.genarate_word_cloud(bvid)
            self._update_statistics()
        except ValueError:
            messagebox.showerror("错误", "请输入有效的BV号")
        except Exception as e:
            messagebox.showerror("错误", str(e))
    def show_line_chart(self):
        try:
            html_path = os.path.join(self.download_path, f"{self.bvid}_line.html")
            self._show_echarts(html_path,"Bilibili弹幕时间分布图")
        except FileNotFoundError:
            messagebox.showerror("错误", "HTML 文件不存在，请先分析数据")
        except Exception as e:
            messagebox.showerror("错误", str(e))
    def _show_echarts(self,html_path,title=""):
        try:
            with open(html_path, "r", encoding="utf-8") as file:
                html_content = file.read()
            webview.create_window(title, html=html_content,width=800, height=600)
            current_width=self.parent.winfo_width()
            current_height=self.parent.winfo_height()
            webview.start()
            self.parent.geometry(f"{current_width}x{current_height}")
        except FileNotFoundError:
            messagebox.showerror("错误", "HTML 文件不存在，请先分析数据")
        except Exception as e:
            messagebox.showerror("错误", str(e))

    def _update_statistics(self):
        stats = self._calculate_statistics()
        for i, (name, value) in enumerate(stats.items()):
            if i < len(self.tree.get_children()):
                self.tree.item(self.tree.get_children()[i], values=(f"{name}: {value}",))
            else:
                self.tree.insert("", tk.END, values=(f"{name}: {value}",))
        messagebox.showinfo("提示", "数据更新成功")


    def _calculate_statistics(self):
        stats = {
            "总弹幕量":self.data.get("danmu_count", "无数据"),
            "用户数量": self.data.get("user_count", "无数据"),
            "平均弹幕量": self.data.get("avg_length", "无数据"),
            "最活跃用户": self.data.get("most_active_user", "无数据"),
            "高频词汇": self.data.get("top_keywords", "无数据")
        }
        return stats

    def _create_wordcloud_tab(self, parent):
        self.wordcloud_frame = ttk.Frame(parent)
        self.wordcloud_frame.pack(fill=tk.BOTH, expand=True)

        self.wordcloud_label = tk.Label(self.wordcloud_frame, text="词云图", font=("Arial", 16))
        self.wordcloud_label.pack(pady=10)

        self.wordcloud_image = tk.Label(self.wordcloud_frame)
        self.wordcloud_image.pack(pady=10)

        self.wordcloud_button = ttk.Button(self.wordcloud_frame, text="▶ 展示词云图", command=lambda :self.show_wordcloud())
        self.wordcloud_button.pack(pady=10)

    def show_wordcloud(self):
        try:
            wordcloud_path = os.path.join(self.download_path, f"{self.bvid}_word_cloud.html")
            self._show_echarts(wordcloud_path,"Bilibili弹幕词云图")
        except FileNotFoundError:
            messagebox.showerror("错误", "词云图文件不存在，请先分析数据")
        except Exception as e:
            messagebox.showerror("错误", str(e))


if __name__ == "__main__":
    root = tk.Tk()
    root.title("弹幕分析")
    root.geometry("800x600")
    bvid="BV11NoCYmEkP"
    analyze_frame = AnalyzeFrame(root,bvid)
    analyze_frame.pack(expand=True, fill="both")
    root.mainloop()
